import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";
import { EntityMetadata } from "typeorm";
import { ColumnMetadata } from "typeorm/metadata/ColumnMetadata";
import { RelationMetadata } from "typeorm/metadata/RelationMetadata";

export async function checkDto(entity: any, dto: any): Promise<boolean> {
    const errors = await validate(plainToInstance(entity, dto));
    if (errors.length > 0) {
        throw new Error(Object.values(errors[0].constraints).join('   '));
    }

    return true;
}

/**
 * 根据Entity元数据中定义的comment,设置Excel文件的列名称
 * @param metadata 
 * @param columns 
 * @returns 
 */
export function getExcelColumnName(metadata: EntityMetadata, columns: Array<string>): {[key: string]: any} {
    const columnNames = {};
    // const transData = this.sharedService.getFormFieldSelectOption();
    for (let index = 0; index < columns.length; index++) {
        const e = columns[index];
        if (e.includes('.')) {
            // console.log('e', e);
            
            const entityPath = e.split('.');
            let relationMeta: RelationMetadata;
            for (let index = 0; index < entityPath.length; index++) {
                if (index === 0) {
                    relationMeta = metadata.findRelationWithPropertyPath(entityPath[index])
                } else if (index === entityPath.length - 1) {
                    columnNames[e] = relationMeta.inverseEntityMetadata.findColumnWithPropertyName(entityPath[index]).comment;        
                } else {
                    relationMeta = relationMeta.inverseEntityMetadata.findRelationWithPropertyPath(entityPath[index]);
                }
            }
            
            
        } else {
            columnNames[e] = metadata.findColumnWithPropertyName(e).comment;
        }
        
    }
    // console.log('columnNames', columnNames);
    
    return columnNames;
}